<script setup lang="ts">
	//店铺装修
	import { onMounted, ref } from "vue";
	import {
		validatePhoneNumber
	} from '@/utlis/common.js'
	import {
		getCurrentInstance
	} from 'vue'
	import {
		onShow,
		onHide,
		onLoad
	} from '@dcloudio/uni-app'
	import form from "../../../uni_modules/uview-plus/libs/config/props/form";
	import {
		userStore
	} from '@/pinia';
	import {
		useRouter
	} from 'uni-mini-router'
	let router = useRouter()
	const userStoreInfo = userStore();
	const {
		proxy,
	} = getCurrentInstance()
	onLoad((options) => {
		if (options.detailId) {
			//回显
			itemId.value = options.detailId
			getDetail(options.postType, options.detailId)
		} else {
			//发布
			pageObj.value = options.id
			getScreen()
		}
	})
	const getDetail = (postType, detailId) => {
		proxy.$req('GET', proxy.$api.richDetail13, {
			userId: userStoreInfo.userInfo.id,
			type: postType == 0 ? 'store' : 'certificate ',
			id: detailId
		}).then((res) => {
			console.log(res, 'res');
			marketType.value = res.result.serviceCenterList
			let da = res.result
			let aa = marketType.value.filter((item) => {
				return item.id == da.categoryId
			})
			console.log(aa);
			gysForm.value.type = aa[0].name
			gysForm.value.typeId = da.categoryId
			gysForm.value.title = da.title
			fileList.value.fileList0 = JSON.parse(da.images)
			gysForm.value.description = da.companyProfile
			fileList.value.fileList1 = JSON.parse(da.companyProfileImgUrl)
			gysForm.value.project = da.decorationCases
			fileList.value.fileList2 = JSON.parse(da.decorationCasesImgUrl)
			gysForm.value.zili = da.companyQualifications
			fileList.value.fileList3 = JSON.parse(da.companyQualificationsImgUrl)
			gysForm.value.fangshi = da.cooperationMethods
			fileList.value.fileList4 = JSON.parse(da.cooperationMethodsImgUrl)
			gysForm.value.companyAddress = da.companyAddress
			gysForm.value.human = da.contactUser
			gysForm.value.phone = da.contactPhone
		})
	}
	onMounted(() => { })
	let itemId = ref('')
	let pageObj = ref({})
	let form1 = ref(null)
	let marketType = ref([])
	const getScreen = () => {
		// 获取服务类型
		proxy.$req('GET', proxy.$api.localService, {
			id: pageObj.value
		}).then((res) => {
			// console.log(res, 'res');
			marketType.value = res.result
		})
	}
	//表单
	let gysForm = ref({
		need: '',
		type: '',
		typeId: '',
		title: '',
		description: '',
		project: '',
		zili: '',
		fangshi: '',
		companyAddress: '',
		human: '',
		phone: '',
	})
	//表单规则
	let gysRules = ref({
		type: {},
		title: {
			required: true,
			message: '请输入正确内容',
			trigger: ['change']
		},
		description: {
			required: false,
			message: '请输入正确内容',
			trigger: ['change']
		},
		project: {
			required: false,
			message: '请输入正确内容',
			trigger: ['change']
		},
		zili: {
			required: false,
			message: '请输入正确内容',
			trigger: ['change']
		},
		fangshi: {
			required: false,
			message: '请输入正确内容',
			trigger: ['change']
		},
		companyAddress: {
			required: true,
			message: '请选择地址',
			trigger: ['change']
		},
		human: {
			required: true,
			message: '请输入正确内容',
			trigger: ['change']
		},
		phone: [{
			required: true,
			message: '手机号码必填',
		},
		{
			validator: (rule, value, callback) => {
				console.log(value);
				return validatePhoneNumber(value);
			},
			message: '手机号码不正确',
			trigger: ['change'],
		}],
	})
	//上传图片
	const afterRead = (e, type) => {
		// console.log(fileList.value[`fileList${type}`], 'fileList[type]');
		// [`fileList${type}`]
		console.log(e);
		const item = e.file;
		// fileList.value[`fileList${type}`].push({
		// 	...item,
		// 	//提示上传中
		// 	status: 'uploading',
		// 	message: '上传中'
		// });
		uni.showLoading({
			title: '上传中',
		})
		for (let a = 0; a <= item.length; a++) {
			uni.uploadFile({
				url: proxy.$uploadUrl + proxy.$api.uploadFile,
				filePath: item[a].url,
				name: 'file',
				formData: {
					file: item[a].url,
				},
				success: (uploadFileRes) => {
					console.log(JSON.parse(uploadFileRes.data));
					if (!JSON.parse(uploadFileRes.data).success) {
						uni.showToast({
							title: JSON.parse(uploadFileRes.data).message,
							icon: 'none'
						})
						// setTimeout(() => {
						// 	fileList.value[`fileList${type}`].splice(-1)
						// }, 700)
						return
					}
					let result = JSON.parse(uploadFileRes.data).result
					// console.log(result, 'result');
					uni.hideLoading()
					fileList.value[`fileList${type}`].push(
						// item[a]
						Object.assign({}, {
							// status: 'success',
							// message: '上传成功',
							url: result,
							thumb: result
						})
					);
					console.log(fileList.value[`fileList${type}`]);
				},
				complete() { }
			});
		}

	}
	//删除图片
	const deletePic = (e, type) => {
		console.log(e);
		fileList.value[`fileList${type}`].splice(e.index, 1)
	}
	//选择类型
	const typeChose = () => {
		let arr = marketType.value.map((item) => {
			return item.name
		})
		// console.log(marketType.value);
		uni.showActionSheet({
			itemList: arr,
			success: function (res) {
				gysForm.value.type = arr[res.tapIndex]
				gysForm.value.typeId = marketType.value[res.tapIndex].id
			},
			fail: function (res) {
				// console.log(res.errMsg);
			}
		});
	}
	//图片列表
	let fileList = ref({
		fileList0: [],
		fileList1: [],
		fileList2: [],
		fileList3: [],
		fileList4: [],
	})
	const submitForm = () => {
		//校验图片
		// Object.keys(gysForm.value).forEach(key => {
		// 	console.log(key);
		// })
		//校验表单内图片和描述至少上传一项
		//设置表单label和上传图片的响应数组对应
		let labelObj = {
			fileList0: 'need',
			fileList1: 'description',
			fileList2: 'project',
			fileList3: 'zili',
			fileList4: 'fangshi',
		}
		let toastObj = {
			need: '请上传缩略图',
			description: '公司介绍图片和文字至少存在一项',
			project: '装修案例图片和文字至少存在一项',
			zili: '公司资质图片和文字至少存在一项',
			fangshi: '合作方式图片和文字至少存在一项',
		}
		let err = ''
		//循环上传图片数组，判断图片和文字是否有一项为空（缩略图没有label，给个固定值）
		Object.keys(fileList.value).forEach((key) => {
			// console.log(key);
			if (fileList.value[key].length < 1 && !gysForm.value[labelObj[key]]) {
				console.log('错误的', key, labelObj[key]);
				err = toastObj[labelObj[key]]
				return
			}
		})
		if (err) {
			uni.showToast({
				title: err,
				icon: 'none'
			})
			return
		}
		//校验表单
		form1.value.validate().then(res => {
			let url;
			if (itemId.value) {
				url = proxy.$api.editPushRichAll
			} else {
				url = proxy.$api.pushRichAll
			}
			proxy.$req('POST', url, {
				id: itemId.value ? itemId.value : '',
				supplierId: userStoreInfo.userInfo.supplier.id,
				categoryId: gysForm.value.typeId,
				title: gysForm.value.title,
				images: JSON.stringify(fileList.value.fileList0),
				companyProfile: gysForm.value.description,
				companyProfileImgUrl: JSON.stringify(fileList.value.fileList1),
				decorationCases: gysForm.value.project,
				decorationCasesImgUrl: JSON.stringify(fileList.value.fileList2),
				companyQualifications: gysForm.value.zili,
				companyQualificationsImgUrl: JSON.stringify(fileList.value.fileList3),
				cooperationMethods: gysForm.value.fangshi,
				cooperationMethodsImgUrl: JSON.stringify(fileList.value.fileList4),
				companyAddress: gysForm.value.companyAddress,
				contactUser: gysForm.value.human,
				contactPhone: gysForm.value.phone,
			}).then((res) => {
				console.log(res, 'ressubmit');
				uni.showToast({
					title: res.message,
					icon: 'none'
				})
				if (res.success) {
					setTimeout(() => {
						uni.$emit('serviceRefash')
						uni.navigateBack()
					}, 600)
				}
			})
		}).catch(errors => {
			console.log(errors);
			uni.showToast({
				title: '请检查表单',
				icon: 'none'
			})
		})
	}
	const addressChecked = (e) => {
		console.log(e.detail.value[0].value);
		// gysForm.value.companyAddress
		gysForm.value.companyAddress = ''
		e.detail.value.map((item) =>
			gysForm.value.companyAddress += item.value
		)
		// console.log(gysForm.value.companyAddress, 'e.detail.value');
	}
	import city from '@/sheng_shi_xian_data.json'
	const goAuth = () => {
		router.push({
			name: 'authRole',
			params: {}
		})
	}
</script>
<template>
	<view style="padding:16rpx 32rpx;background-color: #F2E6E7;" class="r-flex-between-center"
		v-if="userStoreInfo.userFlag==2?userStoreInfo.userInfo.supplier.isReal!=1:userStoreInfo.userFlag==1?userStoreInfo.userInfo.shoppingStore.isReal!=1:false">
		<text style="color: #FF6C6C;font-size: 28rpx;font-weight: 600;">企业未认证，认证后可发布营销信息</text>
		<view style="background-color: #FF6B6B;color: #fff;font-size: 22rpx;padding: 10rpx 20rpx;border-radius: 60rpx;"
			@click="goAuth">
			去认证
			<!-- 认证标记qx -->
		</view>
	</view>
	<view class="form">
		<u--form :model="gysForm" :rules="gysRules" ref="form1" labelPosition="top" labelWidth="150">
			<u-form-item class="formItem " label="" prop="type" @click.stop="typeChose">
				<template #label>
					<view class="r-flex-between-center">
						<view class="">
							<text>*</text>
							<text>服务类型</text>
						</view>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</template>
				<u--input v-model="gysForm.type" border="none" disabled disabledColor="#fff"
					placeholder="请输入"></u--input>
			</u-form-item>
			<u-form-item class="formItem" label="标题" prop="title">
				<u--input v-model="gysForm.title" border="none" placeholder="请输入"></u--input>
			</u-form-item>
			<u-form-item class="formItem" label="缩略图" prop="description">
				<view class="formItemArea">
					<u-upload :fileList="fileList.fileList0" @afterRead="afterRead($event,0)"
						@delete="deletePic($event,0)" name="1" multiple :maxCount="1"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="公司介绍" prop="description">
				<view class="formItemArea">
					<u--textarea v-model="gysForm.description" maxlength="500" count placeholder="请输入内容"
						border="none"></u--textarea>
					<u-upload :fileList="fileList.fileList1" @afterRead="afterRead($event,1)"
						@delete="deletePic($event,1)" name="1" multiple :maxCount="5"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="装修案例" prop="project">
				<view class="formItemArea">
					<u--textarea v-model="gysForm.project" maxlength="500" count placeholder="请输入内容"
						border="none"></u--textarea>
					<u-upload :fileList="fileList.fileList2" @afterRead="afterRead($event,2)"
						@delete="deletePic($event,2)" name="1" multiple :maxCount="5"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="公司资质" prop="zili">
				<view class="formItemArea">
					<u--textarea v-model="gysForm.zili" maxlength="500" count placeholder="请输入内容"
						border="none"></u--textarea>
					<u-upload :fileList="fileList.fileList3" @afterRead="afterRead($event,3)"
						@delete="deletePic($event,3)" name="1" multiple :maxCount="5"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="合作方式" prop="fangshi">
				<view class="formItemArea">
					<u--textarea v-model="gysForm.fangshi" maxlength="500" count placeholder="请输入内容"
						border="none"></u--textarea>
					<u-upload :fileList="fileList.fileList4" @afterRead="afterRead($event,4)"
						@delete="deletePic($event,4)" name="1" multiple :maxCount="5"></u-upload>
				</view>
			</u-form-item>
			<u-form-item class="formItem" label="公司地址" prop="companyAddress">
				<uni-data-picker v-model="gysForm.companyAddress" :localdata="city" popup-title="请选择" :map="{
					text:'label',
					value:'value'
				}" @change="addressChecked">
					<view class="">
						{{gysForm.companyAddress?gysForm.companyAddress:'请选择' }}
					</view>
				</uni-data-picker>
			</u-form-item>
			<u-form-item class="formItem" label="联系人" prop="human">
				<u--input v-model="gysForm.human" border="none" placeholder="请输入"></u--input>
			</u-form-item>
			<u-form-item class="formItem" label="手机号" prop="phone">
				<u--input v-model="gysForm.phone" border="none" placeholder="请输入"></u--input>
			</u-form-item>
		</u--form>
		<view class="gysBtn" @click="submitForm('gysAddMarket')">
			发布
		</view>
	</view>
</template>
<style lang="scss">
	:deep(.input-value-border) {
		border: none !important;
	}

	.form {
		width: 686rpx;
		margin: 0 auto;

		.formItem {
			border-bottom: 1rpx solid #e7e7e7;

			.formItemArea {
				width: 100%;
			}
		}
	}

	.gysBtn {
		width: 686rpx;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		background: #CB645E;
		border-radius: 10rpx;
		color: #fff;
		margin: 50rpx auto;
	}
</style>